import { app, BrowserWindow, globalShortcut, ipcMain, Menu, Tray } from 'electron'
import * as path from 'path'
const isDev = process.env.MODE === 'devlopment'

let win: BrowserWindow
const iconPath = path.join(__dirname, '../icons/linuxTest.png')
function createWindow() {
  win = new BrowserWindow({
    width: 800,
    height: 600,
    // transparent: true,
    frame: false,
    icon: iconPath,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      // nodeIntegration: true,
    },
  })

  if (isDev) {
    win.webContents.openDevTools()
    win.loadURL('http://localhost:9090/')
  } else {
    win.loadFile(path.join(__dirname, '../dist/index.html'))
  }

  ipcMain.on('min', () => {
    win!.minimize()
  })
  ipcMain.on('max', () => {
    if (win!.isMaximized()) {
      win!.restore()
    } else {
      win!.maximize()
    }
  })
  ipcMain.on('close', () => {
    // 最小化到托盘
    win!.hide()

    // win.close()
  })
}
app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })

  // 托盘相关

  const tray = new Tray(iconPath)
  tray.setToolTip('吴昌焕的小工具')

  tray.setContextMenu(
    Menu.buildFromTemplate([
      {
        label: '显示',
        click: () => {
          win!.show()
        },
      },
      {
        label: '退出',
        click: () => {
          app.quit()
        },
      },
    ])
  )

  tray.on('double-click', () => {
    console.log('double-click')
    win!.show()
  })

  // 注册快捷键
  globalShortcut.register('CommandOrControl+F12', () => {
    let focusWin = BrowserWindow.getFocusedWindow()
    focusWin && focusWin.webContents.toggleDevTools()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    globalShortcut.unregisterAll()
    app.quit()
  }
})
